module ActionController
  module Rescue
    alias_method :build_in_rescue_action, :rescue_action        

    def rescue_action(exception)
      ExceptionGrowler.send_growler(exception)
      build_in_rescue_action(exception)
    end          
  end
end

# ExceptionGrowler
module ExceptionGrowler
  class << self        
    
    attr_accessor :application_name
    
    # Configure clients
    def recipients (&block)
      @recipients ||= []
      yield @recipients
    end
    
    # Send out the growler to configured hosts
    def send_growler(exception)
      message_title, message_body = exception.class.to_s, exception.message
      message_title = "[#{application_name}] " + message_title if application_name
            
      @recipients.each do |r|
        begin
          next if r[:environment] && r[:environment] != RAILS_ENV
          next if r[:ignore_404] && exceptions_404.include?(exception.class)
          g = Growl.new r[:host], "ExceptionGrowler", ["exception"], nil, r[:password]
          g.notify("exception", message_title, message_body)
        rescue
        end
      end
    end
    
    # Define a set of exceptions that will be treat as error 404
    def exceptions_404
      [ ActiveRecord::RecordNotFound,
        ActionController::UnknownController,
        ActionController::UnknownAction,
        ActionController::RoutingError
      ]
    end
    
  end
  
end

